﻿/*----------------------------------------------------------------
    Copyright (C) 2022 Senparc
    
    文件名：CustomMessageHandler_Events.cs
    文件功能描述：自定义MessageHandler
    
    
    创建标识：Senparc - 20150312
----------------------------------------------------------------*/

//DPBMARK_FILE MP
using Senparc.CO2NET.Extensions;
using Senparc.NeuChar.Entities;
using Senparc.Weixin.Exceptions;
using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.MP.Entities;
using Senparc.Weixin.Sample.CommonService.Download;
using System;
using System.Linq;
using System.Threading.Tasks;

#if NET462
using System.Web;
#endif


namespace Senparc.Weixin.Sample.CommonService.CustomMessageHandler
{
    /// <summary>
    /// 自定义MessageHandler
    /// </summary>
    public partial class CustomMessageHandler
    {
        public override Task<IResponseMessageBase> OnEvent_ClickRequestAsync(RequestMessageEvent_Click requestMessage)
        {
            return Task.Factory.StartNew<IResponseMessageBase>(() =>
            {
                var syncResponseMessage = OnEvent_ClickRequest(requestMessage);//这里为了保持Demo的连贯性，结果先从同步方法获取，实际使用过程中可以在 OnEvent_ClickRequestAsync 中全部直接定义异步方法
                //常识获取Click事件的同步方法
                if (syncResponseMessage is ResponseMessageText)
                {
                    var textResponseMessage = syncResponseMessage as ResponseMessageText;
                    textResponseMessage.Content += "\r\n\r\n  -- 来自【异步MessageHandler】的回复";
                }

                return syncResponseMessage;
            });
        }

        /// <summary>
        /// 【异步方法】事件之发送模板消息返回结果
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override async Task<IResponseMessageBase> OnEvent_TemplateSendJobFinishRequestAsync(RequestMessageEvent_TemplateSendJobFinish requestMessage)
        {
            switch (requestMessage.Status)
            {
                case "success":
                    //发送成功

                    break;
                case "failed:user block":
                    //送达由于用户拒收（用户设置拒绝接收公众号消息）而失败
                    break;
                case "failed: system failed":
                    //送达由于其他原因失败
                    break;
                default:
                    throw new WeixinException("未知模板消息状态：" + requestMessage.Status);
            }

            //注意：此方法内不能再发送模板消息，否则会造成无限循环！

            try
            {
                var msg = @"已向您发送模板消息
状态：{0}
MsgId：{1}
（这是一条来自MessageHandler的异步客服消息）".FormatWith(requestMessage.Status, requestMessage.MsgID);
                await CustomApi.SendTextAsync(appId, OpenId, msg);//发送客服消息
            }
            catch (Exception e)
            {
                Senparc.Weixin.WeixinTrace.SendCustomLog("模板消息发送失败", e.ToString());
            }


            //无需回复文字内容
            //return requestMessage
            //    .CreateResponseMessage<ResponseMessageNoResponse>();
            return null;
        }

        /// <summary>
        /// 通过二维码扫描关注扫描事件,无论何时扫码，都会建立上下级关联有关系
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override async Task<IResponseMessageBase> OnEvent_ScanRequestAsync(RequestMessageEvent_Scan requestMessage)
        {
            //通过扫描关注
            var responseMessage = CreateResponseMessage<ResponseMessageText>();

            #region 关注数据
            string openid = responseMessage.ToUserName;//关注者或扫码者openid
            string scene_str = requestMessage.EventKey;//带参数二维码场景值
            string strEvent = requestMessage.Event.ToString();//事件

            CoreHelper.LogHelper.Info($"通过二维码扫描关注扫描事件，openid:{openid},场景值:{scene_str},事件:{strEvent}", CoreHelper.LogHelper.logsSource.微信, openid);
            #endregion

            //判断场景值是否为空，并且扫码者openid不等于场景值，即不能自己扫自己
            if (!string.IsNullOrEmpty(scene_str))
            {
                scene_str = scene_str.Replace("qrscene_", "");//场景二维码值

                if (openid != scene_str)
                {
                    //保存推荐人关系
                    //Models.partnersrelationshiptemp model = new Models.partnersrelationshiptemp();
                    //model.openid = openid;//扫码人的openid
                    //model.parentpartnersopenid = scene_str;//推荐人openid
                    //model.createtime = System.DateTime.Now;
                    //await BLL.IFsql.fsql.Insert(model).ExecuteAffrowsAsync();
                }
                else
                {
                    CoreHelper.LogHelper.Info($"不能扫自己的参数二维码，openid:{openid},场景值:{scene_str},事件:{strEvent}", CoreHelper.LogHelper.logsSource.微信, openid);
                }
            }
            return null;
        }
        public override async Task<IResponseMessageBase> OnEvent_SubscribeRequestAsync(RequestMessageEvent_Subscribe requestMessage)
        {
            try
            {
                //只有未关注的用户扫码才会有此事件，关注后再扫码就没有了
                var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageText>(requestMessage);

                #region 关注数据
                string openid = responseMessage.ToUserName;//关注者或扫码者openid
                string scene_str = requestMessage.EventKey;//带参数二维码场景值
                string strEvent = requestMessage.Event.ToString();//事件



                CoreHelper.LogHelper.Info($"第三方平台通过扫描参数二维码订阅(关注)，openid:{openid},场景值:{scene_str},事件:{strEvent},微信号:{responseMessage.FromUserName}", CoreHelper.LogHelper.logsSource.微信, openid);
                #endregion

                //判断场景值是否为空，并且扫码者openid不等于场景值，即不能自己扫自己
                if (!string.IsNullOrEmpty(scene_str))
                {
                    scene_str = scene_str.Replace("qrscene_", "");//场景二维码值

                    if (openid != scene_str)
                    {
                        ////保存推荐人关系
                        //Models.partnersrelationshiptemp model = new Models.partnersrelationshiptemp();
                        //model.openid = openid;//扫码人的openid
                        //model.parentpartnersopenid = scene_str;//推荐人openid
                        //model.createtime = System.DateTime.Now;
                        //await BLL.IFsql.fsql.Insert(model).ExecuteAffrowsAsync();
                    }
                    else
                    {
                        CoreHelper.LogHelper.Info($"不能扫自己的参数二维码，openid:{openid},场景值:{scene_str},事件:{strEvent}", CoreHelper.LogHelper.logsSource.微信, openid);
                    }
                }
                return null;
            }
            catch (Exception ex)
            {
                CoreHelper.LogHelper.Info($"第三方平台通过扫描参数二维码订阅异常，openid:{requestMessage.ToUserName},场景值:{requestMessage.EventKey},事件:{requestMessage.Event.ToString()}", CoreHelper.LogHelper.logsSource.微信, requestMessage.ToUserName, ex);
                return null;
            }
        }

    }
}